/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.application;

import com.jb.web.bean.BaseComponent;
import com.jb.web.bean.Page;
import com.jb.web.bean.UIComponentImpl;
import com.jb.web.bean.inspector.PropertyField;
import com.jb.web.context.WebContext;
import com.jb.web.lifecycle.LifeCycleImpl;

import java.beans.PropertyEditor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Processes request from a popup window
 */
public class DialogBoxApps {
    public static String ID_KEY="com.jb.web.propertyEditor.editingField.id";
    public static String PE_KEY="com.jb.web.propertyEditor.pe";
    public static String DATA_SOURCE="dataSource";
    
    static private Log log = LogFactory.getLog(ApplicationImpl.class.getName());
    /**
     * Creates the popup window
     * @param appl
     * @param request
     * @param response
     * @throws ApplicationException
     * @throws IOException
     */
    public void process(ApplicationImpl appl, HttpServletRequest request, HttpServletResponse response)
        throws ApplicationException, IOException {
        if(log.isDebugEnabled()) {
            log.debug("Start process");
        }
        PropertyField createdFormField = null;
        LifeCycleImpl lifeCycle = new LifeCycleImpl();
        WebContext ctx = appl.makeContext(request, response, lifeCycle);
        BaseComponent requestComponent = ctx.getRequestComponent();
        if ((requestComponent != null) && requestComponent instanceof UIComponentImpl) {
            Page page = ((UIComponentImpl) requestComponent).getPage();

            if (page != null) {
                page.setDialogMode(true);
            }
        }
        //whether this is an internal request
        if (new InternalProcessor().handleRequest(ctx, request, response)) {
            return;
        }

        //id of the property
        String id = request.getParameter("id");

        if ((id != null) && (id.length() > 0)) {
            //store the property id in the session
            ctx.getSession().addAttribute(ID_KEY, id);
        } else {
            //retrieve from session
            id = (String) ctx.getSession().getAttribute(ID_KEY);
        }

        //get property from id
        if (id != null) {
            createdFormField = (PropertyField) ctx.getSession().getDesignComponentById(id);
        }

        PropertyEditor pe = null;
        //find property editor
        if (createdFormField != null) {
            //it has a property editor
            pe = createdFormField.getPropertyEditor(ctx);
        } else {
            ctx.addErrorMessage(this, "Property Field is not defined");
        }

        if (pe != null) {
            //set value as text, so that we can get an object out 
            pe.setAsText(createdFormField.getValue());

            //add property value (a bean)
            ctx.addParameter(DATA_SOURCE, pe.getValue());
            //in event, propertyEditor can be retrieved and set value
            ctx.addParameter(PE_KEY, pe);
        } else {
            ctx.addErrorMessage(createdFormField, "PropertyEditor is not defined");
        }

        //make sure we are in run mode
        boolean oldMode = ctx.isRunTime();
        ctx.getSession().setRunTime(true);
        lifeCycle.execute(ctx);
        //accept submit and apply as signal of submitting the request
        String submit = request.getParameter("submit");
        String apply = request.getParameter("apply");
        //
        if (((submit != null) || (apply != null)) && !ctx.isError()) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(HtmlConstants.DOC_TYPE).append("<HTML ><HEAD>\n").append(HtmlConstants.CONTENT_TYPE)
                        .append("<TITLE>").append(ctx.getResources().get("title")).append("</TITLE>\n")
                        .append(HtmlConstants.getInclude(ctx)).append("</HEAD>\n");

            stringBuffer.append("<BODY style=\"margin:0 0 0 0;\" >\n<div id=" + createdFormField.getClientId() + " >");

            String textValue = pe.getAsText();
            //try to close the popup window here and write the value the field
            stringBuffer.append(textValue + "</div><script>opener.document.getElementById('")
                        .append(createdFormField.getClientId()).append("').value = document.getElementById('")
                        .append(createdFormField.getClientId())
                        .append("').innerHTML;\n opener.document.getElementById('")
                        .append(createdFormField.getClientId())
                        .append("').focus();\n window.close(); </script></BODY></HTML>");
            if(log.isDebugEnabled())
                log.debug("Close Popup window :" + stringBuffer);
            response.getWriter().write(stringBuffer.toString());
        } else {
            Page respondRegion = (Page) ctx.getRespondTree();
            if(respondRegion!=null)
                respondRegion.setDialogMode(true);
            lifeCycle.render(ctx);
        }
        //restore runmode
        ctx.getSession().setRunTime(oldMode);
        ctx.cleanUp();
        if(log.isDebugEnabled()) {
            log.debug("End process");
        }
    }
}
